<!DOCTYPE html><html lang="en" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>史上最最最详细的手写Promise教程 | 孙志豪的博客</title><meta name="author" content="孙志豪"><meta name="copyright" content="孙志豪"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="BAT前端经典面试问题：史上最最最详细的手写Promise教程关注  我们工作中免不了运用promise用来解决异步回调问题。平时用的很多库或者插件都运用了promise 例如axios、fetch等等。但是你知道promise是咋写出来的呢？ 别怕～这里有本promisesA+规范，便宜点10元卖给你了。  1、Promise 的声明首先呢，promise肯定是一个类，我们就用class来声明">
<meta property="og:type" content="article">
<meta property="og:title" content="史上最最最详细的手写Promise教程">
<meta property="og:url" content="https://szhihao.gitee.io/2022/10/11/07-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%89%8B%E5%86%99%E7%AF%87%EF%BC%89/%E6%9C%80%E8%AF%A6%E7%BB%86%E7%9A%84%E6%89%8B%E5%86%99Promise%E6%95%99%E7%A8%8B/index.html">
<meta property="og:site_name" content="孙志豪的博客">
<meta property="og:description" content="BAT前端经典面试问题：史上最最最详细的手写Promise教程关注  我们工作中免不了运用promise用来解决异步回调问题。平时用的很多库或者插件都运用了promise 例如axios、fetch等等。但是你知道promise是咋写出来的呢？ 别怕～这里有本promisesA+规范，便宜点10元卖给你了。  1、Promise 的声明首先呢，promise肯定是一个类，我们就用class来声明">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="https://szhihao.gitee.io/img/%E5%A4%A9%E7%A9%BA.jpeg">
<meta property="article:published_time" content="2022-10-11T12:01:36.000Z">
<meta property="article:modified_time" content="2022-10-11T09:29:35.592Z">
<meta property="article:author" content="孙志豪">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://szhihao.gitee.io/img/%E5%A4%A9%E7%A9%BA.jpeg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://szhihao.gitee.io/2022/10/11/07-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%89%8B%E5%86%99%E7%AF%87%EF%BC%89/%E6%9C%80%E8%AF%A6%E7%BB%86%E7%9A%84%E6%89%8B%E5%86%99Promise%E6%95%99%E7%A8%8B/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","languages":{"hits_empty":"We didn't find any results for the search: ${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: 'Copy successfully',
    error: 'Copy error',
    noSupport: 'The browser does not support'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: 'Just',
    min: 'minutes ago',
    hour: 'hours ago',
    day: 'days ago',
    month: 'months ago'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '史上最最最详细的手写Promise教程',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-10-11 17:29:35'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="/img/%E5%A4%B4%E5%83%8F.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">44</div></a><a href="/tags/"><div class="headline">Tags</div><div class="length-num">1</div></a><a href="/categories/"><div class="headline">Categories</div><div class="length-num">15</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-graduation-cap"></i><span> 博文</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 生活</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/photos/"><i class="fa-fw fa fa-camera-retro"></i><span> 相册</span></a></li><li><a class="site-page child" href="/music/"><i class="fa-fw fa fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 影视</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/links/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/comment/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于笔者</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/img/%E5%A4%A9%E7%A9%BA.jpeg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">孙志豪的博客</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> Search</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-graduation-cap"></i><span> 博文</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 生活</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/photos/"><i class="fa-fw fa fa-camera-retro"></i><span> 相册</span></a></li><li><a class="site-page child" href="/music/"><i class="fa-fw fa fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 影视</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/links/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/comment/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于笔者</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">史上最最最详细的手写Promise教程</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">Created</span><time class="post-meta-date-created" datetime="2022-10-11T12:01:36.000Z" title="Created 2022-10-11 20:01:36">2022-10-11</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">Updated</span><time class="post-meta-date-updated" datetime="2022-10-11T09:29:35.592Z" title="Updated 2022-10-11 17:29:35">2022-10-11</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%89%8B%E5%86%99%E7%AF%87%EF%BC%89/">核心js（手写篇）</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="史上最最最详细的手写Promise教程"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">Post View:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><hr>
<h1 id="BAT前端经典面试问题：史上最最最详细的手写Promise教程"><a href="#BAT前端经典面试问题：史上最最最详细的手写Promise教程" class="headerlink" title="BAT前端经典面试问题：史上最最最详细的手写Promise教程"></a>BAT前端经典面试问题：史上最最最详细的手写Promise教程</h1><p>关注</p>
<p><img src= "" data-lazy-src="https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/6/27/1643f1b42db08dc3~tplv-t2oaga2asx-zoom-crop-mark:1304:1304:1304:734.awebp" alt="BAT前端经典面试问题：史上最最最详细的手写Promise教程"></p>
<p>我们工作中免不了运用promise用来解决异步回调问题。平时用的很多库或者插件都运用了promise 例如axios、fetch等等。但是你知道promise是咋写出来的呢？</p>
<p>别怕～这里有本<a href="https://link.juejin.cn/?target=https://promisesaplus.com">promisesA+规范</a>，便宜点10元卖给你了。</p>
<p><img src= "" data-lazy-src="https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/6/26/1643b4974e9b815b~tplv-t2oaga2asx-watermark.awebp" alt="img"></p>
<h2 id="1、Promise-的声明"><a href="#1、Promise-的声明" class="headerlink" title="1、Promise 的声明"></a>1、Promise 的声明</h2><p>首先呢，promise肯定是一个类，我们就用class来声明。</p>
<ul>
<li>由于<code>new Promise((resolve, reject)=&gt;&#123;&#125;)</code>，所以传入一个参数（函数），<a href="https://link.juejin.cn/?target=https://promisesaplus.com">秘籍</a>里叫他executor，传入就执行。</li>
<li>executor里面有两个参数，一个叫resolve（成功），一个叫reject（失败）。</li>
<li>由于resolve和reject可执行，所以都是函数，我们用let声明。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">class Promise&#123;</span><br><span class="line">  // 构造器</span><br><span class="line">  constructor(executor)&#123;</span><br><span class="line">    // 成功</span><br><span class="line">    let resolve = () =&gt; &#123; &#125;;</span><br><span class="line">    // 失败</span><br><span class="line">    let reject = () =&gt; &#123; &#125;;</span><br><span class="line">    // 立即执行</span><br><span class="line">    executor(resolve, reject);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="解决基本状态"><a href="#解决基本状态" class="headerlink" title="解决基本状态"></a>解决基本状态</h2><h4 id="秘籍对Promise有规定："><a href="#秘籍对Promise有规定：" class="headerlink" title="秘籍对Promise有规定："></a><a href="https://link.juejin.cn/?target=https://promisesaplus.com">秘籍</a>对Promise有规定：</h4><ul>
<li>Promise存在三个状态（state）pending、fulfilled、rejected</li>
<li>pending（等待态）为初始态，并可以转化为fulfilled（成功态）和rejected（失败态）</li>
<li>成功时，不可转为其他状态，且必须有一个不可改变的值（value）</li>
<li>失败时，不可转为其他状态，且必须有一个不可改变的原因（reason）</li>
<li><code>new Promise((resolve, reject)=&gt;&#123;resolve(value)&#125;)</code> resolve为成功，接收参数value，状态改变为fulfilled，不可再次改变。</li>
<li><code>new Promise((resolve, reject)=&gt;&#123;reject(reason)&#125;)</code> reject为失败，接收参数reason，状态改变为rejected，不可再次改变。</li>
<li>若是executor函数报错 直接执行reject();</li>
</ul>
<p>于是乎，我们获得以下代码</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line">class Promise&#123;</span><br><span class="line">  constructor(executor)&#123;</span><br><span class="line">    // 初始化state为等待态</span><br><span class="line">    this.state = &#x27;pending&#x27;;</span><br><span class="line">    // 成功的值</span><br><span class="line">    this.value = undefined;</span><br><span class="line">    // 失败的原因</span><br><span class="line">    this.reason = undefined;</span><br><span class="line">    let resolve = value =&gt; &#123;</span><br><span class="line">      // state改变,resolve调用就会失败</span><br><span class="line">      if (this.state === &#x27;pending&#x27;) &#123;</span><br><span class="line">        // resolve调用后，state转化为成功态</span><br><span class="line">        this.state = &#x27;fulfilled&#x27;;</span><br><span class="line">        // 储存成功的值</span><br><span class="line">        this.value = value;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">    let reject = reason =&gt; &#123;</span><br><span class="line">      // state改变,reject调用就会失败</span><br><span class="line">      if (this.state === &#x27;pending&#x27;) &#123;</span><br><span class="line">        // reject调用后，state转化为失败态</span><br><span class="line">        this.state = &#x27;rejected&#x27;;</span><br><span class="line">        // 储存失败的原因</span><br><span class="line">        this.reason = reason;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">    // 如果executor执行报错，直接执行reject</span><br><span class="line">    try&#123;</span><br><span class="line">      executor(resolve, reject);</span><br><span class="line">    &#125; catch (err) &#123;</span><br><span class="line">      reject(err);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="then方法"><a href="#then方法" class="headerlink" title="then方法"></a>then方法</h2><h4 id="秘籍规定-Promise有一个叫做then的方法，里面有两个参数：onFulfilled-onRejected-成功有成功的值，失败有失败的原因"><a href="#秘籍规定-Promise有一个叫做then的方法，里面有两个参数：onFulfilled-onRejected-成功有成功的值，失败有失败的原因" class="headerlink" title="秘籍规定:Promise有一个叫做then的方法，里面有两个参数：onFulfilled,onRejected,成功有成功的值，失败有失败的原因"></a><a href="https://link.juejin.cn/?target=https://promisesaplus.com">秘籍</a>规定:Promise有一个叫做then的方法，里面有两个参数：onFulfilled,onRejected,成功有成功的值，失败有失败的原因</h4><ul>
<li>当状态state为fulfilled，则执行onFulfilled，传入this.value。当状态state为rejected，则执行onRejected，传入this.reason</li>
<li>onFulfilled,onRejected如果他们是函数，则必须分别在fulfilled，rejected后被调用，value或reason依次作为他们的第一个参数</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">class Promise&#123;</span><br><span class="line">  constructor(executor)&#123;...&#125;</span><br><span class="line">  // then 方法 有两个参数onFulfilled onRejected</span><br><span class="line">  then(onFulfilled,onRejected) &#123;</span><br><span class="line">    // 状态为fulfilled，执行onFulfilled，传入成功的值</span><br><span class="line">    if (this.state === &#x27;fulfilled&#x27;) &#123;</span><br><span class="line">      onFulfilled(this.value);</span><br><span class="line">    &#125;;</span><br><span class="line">    // 状态为rejected，执行onRejected，传入失败的原因</span><br><span class="line">    if (this.state === &#x27;rejected&#x27;) &#123;</span><br><span class="line">      onRejected(this.reason);</span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>这下武学初成，可以对付对付江湖小杂毛了，但是对于带setTimeout的江洋大盗还是没辙。</p>
<p><img src= "" data-lazy-src="https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/6/26/1643b5a767468b4c~tplv-t2oaga2asx-watermark.awebp" alt="img"></p>
<h2 id="解决异步实现"><a href="#解决异步实现" class="headerlink" title="解决异步实现"></a>解决异步实现</h2><p><strong>现在基本可以实现简单的同步代码，但是当resolve在setTomeout内执行，then时state还是pending等待状态 我们就需要在then调用的时候，将成功和失败存到各自的数组，一旦reject或者resolve，就调用它们</strong></p>
<p>类似于发布订阅，先将then里面的两个函数储存起来，由于一个promise可以有多个then，所以存在同一个数组内。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">// 多个then的情况</span><br><span class="line">let p = new Promise();</span><br><span class="line">p.then();</span><br><span class="line">p.then();</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>成功或者失败时，forEach调用它们</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line">class Promise&#123;</span><br><span class="line">  constructor(executor)&#123;</span><br><span class="line">    this.state = &#x27;pending&#x27;;</span><br><span class="line">    this.value = undefined;</span><br><span class="line">    this.reason = undefined;</span><br><span class="line">    // 成功存放的数组</span><br><span class="line">    this.onResolvedCallbacks = [];</span><br><span class="line">    // 失败存放法数组</span><br><span class="line">    this.onRejectedCallbacks = [];</span><br><span class="line">    let resolve = value =&gt; &#123;</span><br><span class="line">      if (this.state === &#x27;pending&#x27;) &#123;</span><br><span class="line">        this.state = &#x27;fulfilled&#x27;;</span><br><span class="line">        this.value = value;</span><br><span class="line">        // 一旦resolve执行，调用成功数组的函数</span><br><span class="line">        this.onResolvedCallbacks.forEach(fn=&gt;fn());</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">    let reject = reason =&gt; &#123;</span><br><span class="line">      if (this.state === &#x27;pending&#x27;) &#123;</span><br><span class="line">        this.state = &#x27;rejected&#x27;;</span><br><span class="line">        this.reason = reason;</span><br><span class="line">        // 一旦reject执行，调用失败数组的函数</span><br><span class="line">        this.onRejectedCallbacks.forEach(fn=&gt;fn());</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">    try&#123;</span><br><span class="line">      executor(resolve, reject);</span><br><span class="line">    &#125; catch (err) &#123;</span><br><span class="line">      reject(err);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  then(onFulfilled,onRejected) &#123;</span><br><span class="line">    if (this.state === &#x27;fulfilled&#x27;) &#123;</span><br><span class="line">      onFulfilled(this.value);</span><br><span class="line">    &#125;;</span><br><span class="line">    if (this.state === &#x27;rejected&#x27;) &#123;</span><br><span class="line">      onRejected(this.reason);</span><br><span class="line">    &#125;;</span><br><span class="line">    // 当状态state为pending时</span><br><span class="line">    if (this.state === &#x27;pending&#x27;) &#123;</span><br><span class="line">      // onFulfilled传入到成功数组</span><br><span class="line">      this.onResolvedCallbacks.push(()=&gt;&#123;</span><br><span class="line">        onFulfilled(this.value);</span><br><span class="line">      &#125;)</span><br><span class="line">      // onRejected传入到失败数组</span><br><span class="line">      this.onRejectedCallbacks.push(()=&gt;&#123;</span><br><span class="line">        onRejected(this.reason);</span><br><span class="line">      &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="解决链式调用"><a href="#解决链式调用" class="headerlink" title="解决链式调用"></a>解决链式调用</h2><p><strong>我门常常用到<code>new Promise().then().then()</code>,这就是链式调用，用来解决回调地狱</strong></p>
<p>1、为了达成链式，我们默认在第一个then里返回一个promise。<a href="https://link.juejin.cn/?target=https://promisesaplus.com">秘籍</a>规定了一种方法，就是在then里面返回一个新的promise,称为promise2：<code>promise2 = new Promise((resolve, reject)=&gt;&#123;&#125;)</code></p>
<ul>
<li>将这个promise2返回的值传递到下一个then中</li>
<li>如果返回一个普通的值，则将普通的值传递给下一个then中</li>
</ul>
<p>2、当我们在第一个then中<code>return</code>了一个参数（参数未知，需判断）。这个return出来的新的promise就是onFulfilled()或onRejected()的值</p>
<p><a href="https://link.juejin.cn/?target=https://promisesaplus.com">秘籍</a>则规定onFulfilled()或onRejected()的值，即第一个then返回的值，叫做x，判断x的函数叫做resolvePromise</p>
<ul>
<li>首先，要看x是不是promise。</li>
<li>如果是promise，则取它的结果，作为新的promise2成功的结果</li>
<li>如果是普通值，直接作为promise2成功的结果</li>
<li>所以要比较x和promise2</li>
<li>resolvePromise的参数有promise2（默认返回的promise）、x（我们自己<code>return</code>的对象）、resolve、reject</li>
<li>resolve和reject是promise2的</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line">class Promise&#123;</span><br><span class="line">  constructor(executor)&#123;</span><br><span class="line">    this.state = &#x27;pending&#x27;;</span><br><span class="line">    this.value = undefined;</span><br><span class="line">    this.reason = undefined;</span><br><span class="line">    this.onResolvedCallbacks = [];</span><br><span class="line">    this.onRejectedCallbacks = [];</span><br><span class="line">    let resolve = value =&gt; &#123;</span><br><span class="line">      if (this.state === &#x27;pending&#x27;) &#123;</span><br><span class="line">        this.state = &#x27;fulfilled&#x27;;</span><br><span class="line">        this.value = value;</span><br><span class="line">        this.onResolvedCallbacks.forEach(fn=&gt;fn());</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">    let reject = reason =&gt; &#123;</span><br><span class="line">      if (this.state === &#x27;pending&#x27;) &#123;</span><br><span class="line">        this.state = &#x27;rejected&#x27;;</span><br><span class="line">        this.reason = reason;</span><br><span class="line">        this.onRejectedCallbacks.forEach(fn=&gt;fn());</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">    try&#123;</span><br><span class="line">      executor(resolve, reject);</span><br><span class="line">    &#125; catch (err) &#123;</span><br><span class="line">      reject(err);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  then(onFulfilled,onRejected) &#123;</span><br><span class="line">    // 声明返回的promise2</span><br><span class="line">    let promise2 = new Promise((resolve, reject)=&gt;&#123;</span><br><span class="line">      if (this.state === &#x27;fulfilled&#x27;) &#123;</span><br><span class="line">        let x = onFulfilled(this.value);</span><br><span class="line">        // resolvePromise函数，处理自己return的promise和默认的promise2的关系</span><br><span class="line">        resolvePromise(promise2, x, resolve, reject);</span><br><span class="line">      &#125;;</span><br><span class="line">      if (this.state === &#x27;rejected&#x27;) &#123;</span><br><span class="line">        let x = onRejected(this.reason);</span><br><span class="line">        resolvePromise(promise2, x, resolve, reject);</span><br><span class="line">      &#125;;</span><br><span class="line">      if (this.state === &#x27;pending&#x27;) &#123;</span><br><span class="line">        this.onResolvedCallbacks.push(()=&gt;&#123;</span><br><span class="line">          let x = onFulfilled(this.value);</span><br><span class="line">          resolvePromise(promise2, x, resolve, reject);</span><br><span class="line">        &#125;)</span><br><span class="line">        this.onRejectedCallbacks.push(()=&gt;&#123;</span><br><span class="line">          let x = onRejected(this.reason);</span><br><span class="line">          resolvePromise(promise2, x, resolve, reject);</span><br><span class="line">        &#125;)</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">    // 返回promise，完成链式</span><br><span class="line">    return promise2;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="完成resolvePromise函数"><a href="#完成resolvePromise函数" class="headerlink" title="完成resolvePromise函数"></a>完成resolvePromise函数</h2><p><a href="https://link.juejin.cn/?target=https://promisesaplus.com">秘籍</a>规定了一段代码，让不同的promise代码互相套用，叫做resolvePromise</p>
<ul>
<li>如果 x &#x3D;&#x3D;&#x3D; promise2，则是会造成循环引用，自己等待自己完成，则报“循环引用”错误</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">let p = new Promise(resolve =&gt; &#123;</span><br><span class="line">  resolve(0);</span><br><span class="line">&#125;);</span><br><span class="line">var p2 = p.then(data =&gt; &#123;</span><br><span class="line">  // 循环引用，自己等待自己完成，一辈子完不成</span><br><span class="line">  return p2;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>1、判断x</p>
<ul>
<li><strong>Otherwise, if x is an object or function,Let then be x.then</strong></li>
<li>x 不能是null</li>
<li>x 是普通值 直接resolve(x)</li>
<li>x 是对象或者函数（包括promise），<code>let then = x.then</code> 2、当x是对象或者函数（默认promise）</li>
<li>声明了then</li>
<li>如果取then报错，则走reject()</li>
<li>如果then是个函数，则用call执行then，第一个参数是this，后面是成功的回调和失败的回调</li>
<li>如果成功的回调还是pormise，就递归继续解析 3、成功和失败只能调用一个 所以设定一个called来防止多次调用</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line">function resolvePromise(promise2, x, resolve, reject)&#123;</span><br><span class="line">  // 循环引用报错</span><br><span class="line">  if(x === promise2)&#123;</span><br><span class="line">    // reject报错</span><br><span class="line">    return reject(new TypeError(&#x27;Chaining cycle detected for promise&#x27;));</span><br><span class="line">  &#125;</span><br><span class="line">  // 防止多次调用</span><br><span class="line">  let called;</span><br><span class="line">  // x不是null 且x是对象或者函数</span><br><span class="line">  if (x != null &amp;&amp; (typeof x === &#x27;object&#x27; || typeof x === &#x27;function&#x27;)) &#123;</span><br><span class="line">    try &#123;</span><br><span class="line">      // A+规定，声明then = x的then方法</span><br><span class="line">      let then = x.then;</span><br><span class="line">      // 如果then是函数，就默认是promise了</span><br><span class="line">      if (typeof then === &#x27;function&#x27;) &#123; </span><br><span class="line">        // 就让then执行 第一个参数是this   后面是成功的回调 和 失败的回调</span><br><span class="line">        then.call(x, y =&gt; &#123;</span><br><span class="line">          // 成功和失败只能调用一个</span><br><span class="line">          if (called) return;</span><br><span class="line">          called = true;</span><br><span class="line">          // resolve的结果依旧是promise 那就继续解析</span><br><span class="line">          resolvePromise(promise2, y, resolve, reject);</span><br><span class="line">        &#125;, err =&gt; &#123;</span><br><span class="line">          // 成功和失败只能调用一个</span><br><span class="line">          if (called) return;</span><br><span class="line">          called = true;</span><br><span class="line">          reject(err);// 失败了就失败了</span><br><span class="line">        &#125;)</span><br><span class="line">      &#125; else &#123;</span><br><span class="line">        resolve(x); // 直接成功即可</span><br><span class="line">      &#125;</span><br><span class="line">    &#125; catch (e) &#123;</span><br><span class="line">      // 也属于失败</span><br><span class="line">      if (called) return;</span><br><span class="line">      called = true;</span><br><span class="line">      // 取then出错了那就不要在继续执行了</span><br><span class="line">      reject(e); </span><br><span class="line">    &#125;</span><br><span class="line">  &#125; else &#123;</span><br><span class="line">    resolve(x);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="解决其他问题"><a href="#解决其他问题" class="headerlink" title="解决其他问题"></a>解决其他问题</h2><p>1、<a href="https://link.juejin.cn/?target=https://promisesaplus.com">秘籍</a>规定onFulfilled,onRejected都是可选参数，如果他们不是函数，必须被忽略</p>
<ul>
<li>onFulfilled返回一个普通的值，成功时直接等于 <code>value =&gt; value</code></li>
<li>onRejected返回一个普通的值，失败时如果直接等于 value &#x3D;&gt; value，则会跑到下一个then中的onFulfilled中，所以直接扔出一个错误<code>reason =&gt; throw err</code> 2、<a href="https://link.juejin.cn/?target=https://promisesaplus.com">秘籍</a>规定onFulfilled或onRejected不能同步被调用，必须异步调用。我们就用setTimeout解决异步问题</li>
<li>如果onFulfilled或onRejected报错，则直接返回reject()</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br></pre></td><td class="code"><pre><span class="line">class Promise&#123;</span><br><span class="line">  constructor(executor)&#123;</span><br><span class="line">    this.state = &#x27;pending&#x27;;</span><br><span class="line">    this.value = undefined;</span><br><span class="line">    this.reason = undefined;</span><br><span class="line">    this.onResolvedCallbacks = [];</span><br><span class="line">    this.onRejectedCallbacks = [];</span><br><span class="line">    let resolve = value =&gt; &#123;</span><br><span class="line">      if (this.state === &#x27;pending&#x27;) &#123;</span><br><span class="line">        this.state = &#x27;fulfilled&#x27;;</span><br><span class="line">        this.value = value;</span><br><span class="line">        this.onResolvedCallbacks.forEach(fn=&gt;fn());</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">    let reject = reason =&gt; &#123;</span><br><span class="line">      if (this.state === &#x27;pending&#x27;) &#123;</span><br><span class="line">        this.state = &#x27;rejected&#x27;;</span><br><span class="line">        this.reason = reason;</span><br><span class="line">        this.onRejectedCallbacks.forEach(fn=&gt;fn());</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">    try&#123;</span><br><span class="line">      executor(resolve, reject);</span><br><span class="line">    &#125; catch (err) &#123;</span><br><span class="line">      reject(err);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  then(onFulfilled,onRejected) &#123;</span><br><span class="line">    // onFulfilled如果不是函数，就忽略onFulfilled，直接返回value</span><br><span class="line">    onFulfilled = typeof onFulfilled === &#x27;function&#x27; ? onFulfilled : value =&gt; value;</span><br><span class="line">    // onRejected如果不是函数，就忽略onRejected，直接扔出错误</span><br><span class="line">    onRejected = typeof onRejected === &#x27;function&#x27; ? onRejected : err =&gt; &#123; throw err &#125;;</span><br><span class="line">    let promise2 = new Promise((resolve, reject) =&gt; &#123;</span><br><span class="line">      if (this.state === &#x27;fulfilled&#x27;) &#123;</span><br><span class="line">        // 异步</span><br><span class="line">        setTimeout(() =&gt; &#123;</span><br><span class="line">          try &#123;</span><br><span class="line">            let x = onFulfilled(this.value);</span><br><span class="line">            resolvePromise(promise2, x, resolve, reject);</span><br><span class="line">          &#125; catch (e) &#123;</span><br><span class="line">            reject(e);</span><br><span class="line">          &#125;</span><br><span class="line">        &#125;, 0);</span><br><span class="line">      &#125;;</span><br><span class="line">      if (this.state === &#x27;rejected&#x27;) &#123;</span><br><span class="line">        // 异步</span><br><span class="line">        setTimeout(() =&gt; &#123;</span><br><span class="line">          // 如果报错</span><br><span class="line">          try &#123;</span><br><span class="line">            let x = onRejected(this.reason);</span><br><span class="line">            resolvePromise(promise2, x, resolve, reject);</span><br><span class="line">          &#125; catch (e) &#123;</span><br><span class="line">            reject(e);</span><br><span class="line">          &#125;</span><br><span class="line">        &#125;, 0);</span><br><span class="line">      &#125;;</span><br><span class="line">      if (this.state === &#x27;pending&#x27;) &#123;</span><br><span class="line">        this.onResolvedCallbacks.push(() =&gt; &#123;</span><br><span class="line">          // 异步</span><br><span class="line">          setTimeout(() =&gt; &#123;</span><br><span class="line">            try &#123;</span><br><span class="line">              let x = onFulfilled(this.value);</span><br><span class="line">              resolvePromise(promise2, x, resolve, reject);</span><br><span class="line">            &#125; catch (e) &#123;</span><br><span class="line">              reject(e);</span><br><span class="line">            &#125;</span><br><span class="line">          &#125;, 0);</span><br><span class="line">        &#125;);</span><br><span class="line">        this.onRejectedCallbacks.push(() =&gt; &#123;</span><br><span class="line">          // 异步</span><br><span class="line">          setTimeout(() =&gt; &#123;</span><br><span class="line">            try &#123;</span><br><span class="line">              let x = onRejected(this.reason);</span><br><span class="line">              resolvePromise(promise2, x, resolve, reject);</span><br><span class="line">            &#125; catch (e) &#123;</span><br><span class="line">              reject(e);</span><br><span class="line">            &#125;</span><br><span class="line">          &#125;, 0)</span><br><span class="line">        &#125;);</span><br><span class="line">      &#125;;</span><br><span class="line">    &#125;);</span><br><span class="line">    // 返回promise，完成链式</span><br><span class="line">    return promise2;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="大功告成"><a href="#大功告成" class="headerlink" title="大功告成"></a>大功告成</h2><p><img src= "" data-lazy-src="https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/6/27/1643f03d413c4ce8~tplv-t2oaga2asx-watermark.awebp" alt="img"></p>
<p>顺便附赠catch和resolve、reject、race、all方法</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br></pre></td><td class="code"><pre><span class="line">class Promise&#123;</span><br><span class="line">  constructor(executor)&#123;</span><br><span class="line">    this.state = &#x27;pending&#x27;;</span><br><span class="line">    this.value = undefined;</span><br><span class="line">    this.reason = undefined;</span><br><span class="line">    this.onResolvedCallbacks = [];</span><br><span class="line">    this.onRejectedCallbacks = [];</span><br><span class="line">    let resolve = value =&gt; &#123;</span><br><span class="line">      if (this.state === &#x27;pending&#x27;) &#123;</span><br><span class="line">        this.state = &#x27;fulfilled&#x27;;</span><br><span class="line">        this.value = value;</span><br><span class="line">        this.onResolvedCallbacks.forEach(fn=&gt;fn());</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">    let reject = reason =&gt; &#123;</span><br><span class="line">      if (this.state === &#x27;pending&#x27;) &#123;</span><br><span class="line">        this.state = &#x27;rejected&#x27;;</span><br><span class="line">        this.reason = reason;</span><br><span class="line">        this.onRejectedCallbacks.forEach(fn=&gt;fn());</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">    try&#123;</span><br><span class="line">      executor(resolve, reject);</span><br><span class="line">    &#125; catch (err) &#123;</span><br><span class="line">      reject(err);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  then(onFulfilled,onRejected) &#123;</span><br><span class="line">    onFulfilled = typeof onFulfilled === &#x27;function&#x27; ? onFulfilled : value =&gt; value;</span><br><span class="line">    onRejected = typeof onRejected === &#x27;function&#x27; ? onRejected : err =&gt; &#123; throw err &#125;;</span><br><span class="line">    let promise2 = new Promise((resolve, reject) =&gt; &#123;</span><br><span class="line">      if (this.state === &#x27;fulfilled&#x27;) &#123;</span><br><span class="line">        setTimeout(() =&gt; &#123;</span><br><span class="line">          try &#123;</span><br><span class="line">            let x = onFulfilled(this.value);</span><br><span class="line">            resolvePromise(promise2, x, resolve, reject);</span><br><span class="line">          &#125; catch (e) &#123;</span><br><span class="line">            reject(e);</span><br><span class="line">          &#125;</span><br><span class="line">        &#125;, 0);</span><br><span class="line">      &#125;;</span><br><span class="line">      if (this.state === &#x27;rejected&#x27;) &#123;</span><br><span class="line">        setTimeout(() =&gt; &#123;</span><br><span class="line">          try &#123;</span><br><span class="line">            let x = onRejected(this.reason);</span><br><span class="line">            resolvePromise(promise2, x, resolve, reject);</span><br><span class="line">          &#125; catch (e) &#123;</span><br><span class="line">            reject(e);</span><br><span class="line">          &#125;</span><br><span class="line">        &#125;, 0);</span><br><span class="line">      &#125;;</span><br><span class="line">      if (this.state === &#x27;pending&#x27;) &#123;</span><br><span class="line">        this.onResolvedCallbacks.push(() =&gt; &#123;</span><br><span class="line">          setTimeout(() =&gt; &#123;</span><br><span class="line">            try &#123;</span><br><span class="line">              let x = onFulfilled(this.value);</span><br><span class="line">              resolvePromise(promise2, x, resolve, reject);</span><br><span class="line">            &#125; catch (e) &#123;</span><br><span class="line">              reject(e);</span><br><span class="line">            &#125;</span><br><span class="line">          &#125;, 0);</span><br><span class="line">        &#125;);</span><br><span class="line">        this.onRejectedCallbacks.push(() =&gt; &#123;</span><br><span class="line">          setTimeout(() =&gt; &#123;</span><br><span class="line">            try &#123;</span><br><span class="line">              let x = onRejected(this.reason);</span><br><span class="line">              resolvePromise(promise2, x, resolve, reject);</span><br><span class="line">            &#125; catch (e) &#123;</span><br><span class="line">              reject(e);</span><br><span class="line">            &#125;</span><br><span class="line">          &#125;, 0)</span><br><span class="line">        &#125;);</span><br><span class="line">      &#125;;</span><br><span class="line">    &#125;);</span><br><span class="line">    return promise2;</span><br><span class="line">  &#125;</span><br><span class="line">  catch(fn)&#123;</span><br><span class="line">    return this.then(null,fn);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line">function resolvePromise(promise2, x, resolve, reject)&#123;</span><br><span class="line">  if(x === promise2)&#123;</span><br><span class="line">    return reject(new TypeError(&#x27;Chaining cycle detected for promise&#x27;));</span><br><span class="line">  &#125;</span><br><span class="line">  let called;</span><br><span class="line">  if (x != null &amp;&amp; (typeof x === &#x27;object&#x27; || typeof x === &#x27;function&#x27;)) &#123;</span><br><span class="line">    try &#123;</span><br><span class="line">      let then = x.then;</span><br><span class="line">      if (typeof then === &#x27;function&#x27;) &#123; </span><br><span class="line">        then.call(x, y =&gt; &#123;</span><br><span class="line">          if(called)return;</span><br><span class="line">          called = true;</span><br><span class="line">          resolvePromise(promise2, y, resolve, reject);</span><br><span class="line">        &#125;, err =&gt; &#123;</span><br><span class="line">          if(called)return;</span><br><span class="line">          called = true;</span><br><span class="line">          reject(err);</span><br><span class="line">        &#125;)</span><br><span class="line">      &#125; else &#123;</span><br><span class="line">        resolve(x);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125; catch (e) &#123;</span><br><span class="line">      if(called)return;</span><br><span class="line">      called = true;</span><br><span class="line">      reject(e); </span><br><span class="line">    &#125;</span><br><span class="line">  &#125; else &#123;</span><br><span class="line">    resolve(x);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line">//resolve方法</span><br><span class="line">Promise.resolve = function(val)&#123;</span><br><span class="line">  return new Promise((resolve,reject)=&gt;&#123;</span><br><span class="line">    resolve(val)</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br><span class="line">//reject方法</span><br><span class="line">Promise.reject = function(val)&#123;</span><br><span class="line">  return new Promise((resolve,reject)=&gt;&#123;</span><br><span class="line">    reject(val)</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br><span class="line">//race方法 </span><br><span class="line">Promise.race = function(promises)&#123;</span><br><span class="line">  return new Promise((resolve,reject)=&gt;&#123;</span><br><span class="line">    for(let i=0;i&lt;promises.length;i++)&#123;</span><br><span class="line">      promises[i].then(resolve,reject)</span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br><span class="line">//all方法(获取所有的promise，都执行then，把结果放到数组，一起返回)</span><br><span class="line">Promise.all = function(promises)&#123;</span><br><span class="line">  let arr = [];</span><br><span class="line">  let i = 0;</span><br><span class="line">  function processData(index,data)&#123;</span><br><span class="line">    arr[index] = data;</span><br><span class="line">    i++;</span><br><span class="line">    if(i == promises.length)&#123;</span><br><span class="line">      resolve(arr);</span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;;</span><br><span class="line">  return new Promise((resolve,reject)=&gt;&#123;</span><br><span class="line">    for(let i=0;i&lt;promises.length;i++)&#123;</span><br><span class="line">      promises[i].then(data=&gt;&#123;</span><br><span class="line">        processData(i,data);</span><br><span class="line">      &#125;,reject);</span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="如何验证我们的promise是否正确"><a href="#如何验证我们的promise是否正确" class="headerlink" title="如何验证我们的promise是否正确"></a>如何验证我们的promise是否正确</h2><p>1、先在后面加上下述代码</p>
<p>2、npm 有一个promises-aplus-tests插件 npm i promises-aplus-tests -g 可以全局安装 mac用户最前面加上sudo</p>
<p>3、命令行 promises-aplus-tests [js文件名] 即可验证</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">// 目前是通过他测试 他会测试一个对象</span><br><span class="line">// 语法糖</span><br><span class="line">Promise.defer = Promise.deferred = function () &#123;</span><br><span class="line">  let dfd = &#123;&#125;</span><br><span class="line">  dfd.promise = new Promise((resolve,reject)=&gt;&#123;</span><br><span class="line">    dfd.resolve = resolve;</span><br><span class="line">    dfd.reject = reject;</span><br><span class="line">  &#125;);</span><br><span class="line">  return dfd;</span><br><span class="line">&#125;</span><br><span class="line">module.exports = Promise;</span><br><span class="line">//npm install promises-aplus-tests 用来测试自己的promise 符不符合promisesA+规范</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<hr>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">Author: </span><span class="post-copyright-info"><a href="https://szhihao.gitee.io">孙志豪</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">Link: </span><span class="post-copyright-info"><a href="https://szhihao.gitee.io/2022/10/11/07-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%89%8B%E5%86%99%E7%AF%87%EF%BC%89/%E6%9C%80%E8%AF%A6%E7%BB%86%E7%9A%84%E6%89%8B%E5%86%99Promise%E6%95%99%E7%A8%8B/">https://szhihao.gitee.io/2022/10/11/07-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%89%8B%E5%86%99%E7%AF%87%EF%BC%89/%E6%9C%80%E8%AF%A6%E7%BB%86%E7%9A%84%E6%89%8B%E5%86%99Promise%E6%95%99%E7%A8%8B/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">Copyright Notice: </span><span class="post-copyright-info">All articles in this blog are licensed under <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> unless stating additionally.</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="/img/%E5%A4%A9%E7%A9%BA.jpeg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2022/10/11/07-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%89%8B%E5%86%99%E7%AF%87%EF%BC%89/%E5%B8%B8%E7%94%A8%E7%9A%84%E5%87%BD%E6%95%B0%E5%B0%81%E8%A3%85/"><img class="prev-cover" src= "" data-lazy-src="/img/%E5%A4%A9%E7%A9%BA.jpeg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">Previous Post</div><div class="prev_info">JavaScript中的一些实用的工具函数</div></div></a></div><div class="next-post pull-right"><a href="/2022/10/11/07-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%89%8B%E5%86%99%E7%AF%87%EF%BC%89/%E7%AE%80%E4%B9%A6%E5%87%BD%E6%95%B0%E5%B0%81%E8%A3%85/"><img class="next-cover" src= "" data-lazy-src="/img/%E5%A4%A9%E7%A9%BA.jpeg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">Next Post</div><div class="next_info">简书函数封装</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="/img/%E5%A4%B4%E5%83%8F.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">孙志豪</div><div class="author-info__description">吾日三省吾身：为人谋而不忠乎？与朋友交而不信乎？传不习乎？</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">44</div></a><a href="/tags/"><div class="headline">Tags</div><div class="length-num">1</div></a><a href="/categories/"><div class="headline">Categories</div><div class="length-num">15</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/szhihao/szhihao"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitee.com/szhihao/szhihao" target="_blank" title="Gitee"><i class="fab fa-github"></i></a><a class="social-icon" href="https://blog.csdn.net/qq_54753561" target="_blank" title="CSDN"><i class="fa fa-book-open"></i></a><a class="social-icon" href="mailto:zhihaomail@qq.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>Announcement</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>Catalog</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#BAT%E5%89%8D%E7%AB%AF%E7%BB%8F%E5%85%B8%E9%9D%A2%E8%AF%95%E9%97%AE%E9%A2%98%EF%BC%9A%E5%8F%B2%E4%B8%8A%E6%9C%80%E6%9C%80%E6%9C%80%E8%AF%A6%E7%BB%86%E7%9A%84%E6%89%8B%E5%86%99Promise%E6%95%99%E7%A8%8B"><span class="toc-number">1.</span> <span class="toc-text">BAT前端经典面试问题：史上最最最详细的手写Promise教程</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81Promise-%E7%9A%84%E5%A3%B0%E6%98%8E"><span class="toc-number">1.1.</span> <span class="toc-text">1、Promise 的声明</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%A7%A3%E5%86%B3%E5%9F%BA%E6%9C%AC%E7%8A%B6%E6%80%81"><span class="toc-number">1.2.</span> <span class="toc-text">解决基本状态</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%A7%98%E7%B1%8D%E5%AF%B9Promise%E6%9C%89%E8%A7%84%E5%AE%9A%EF%BC%9A"><span class="toc-number">1.2.0.1.</span> <span class="toc-text">秘籍对Promise有规定：</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#then%E6%96%B9%E6%B3%95"><span class="toc-number">1.3.</span> <span class="toc-text">then方法</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%A7%98%E7%B1%8D%E8%A7%84%E5%AE%9A-Promise%E6%9C%89%E4%B8%80%E4%B8%AA%E5%8F%AB%E5%81%9Athen%E7%9A%84%E6%96%B9%E6%B3%95%EF%BC%8C%E9%87%8C%E9%9D%A2%E6%9C%89%E4%B8%A4%E4%B8%AA%E5%8F%82%E6%95%B0%EF%BC%9AonFulfilled-onRejected-%E6%88%90%E5%8A%9F%E6%9C%89%E6%88%90%E5%8A%9F%E7%9A%84%E5%80%BC%EF%BC%8C%E5%A4%B1%E8%B4%A5%E6%9C%89%E5%A4%B1%E8%B4%A5%E7%9A%84%E5%8E%9F%E5%9B%A0"><span class="toc-number">1.3.0.1.</span> <span class="toc-text">秘籍规定:Promise有一个叫做then的方法，里面有两个参数：onFulfilled,onRejected,成功有成功的值，失败有失败的原因</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%A7%A3%E5%86%B3%E5%BC%82%E6%AD%A5%E5%AE%9E%E7%8E%B0"><span class="toc-number">1.4.</span> <span class="toc-text">解决异步实现</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%A7%A3%E5%86%B3%E9%93%BE%E5%BC%8F%E8%B0%83%E7%94%A8"><span class="toc-number">1.5.</span> <span class="toc-text">解决链式调用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AE%8C%E6%88%90resolvePromise%E5%87%BD%E6%95%B0"><span class="toc-number">1.6.</span> <span class="toc-text">完成resolvePromise函数</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%A7%A3%E5%86%B3%E5%85%B6%E4%BB%96%E9%97%AE%E9%A2%98"><span class="toc-number">1.7.</span> <span class="toc-text">解决其他问题</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A4%A7%E5%8A%9F%E5%91%8A%E6%88%90"><span class="toc-number">1.8.</span> <span class="toc-text">大功告成</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A6%82%E4%BD%95%E9%AA%8C%E8%AF%81%E6%88%91%E4%BB%AC%E7%9A%84promise%E6%98%AF%E5%90%A6%E6%AD%A3%E7%A1%AE"><span class="toc-number">1.9.</span> <span class="toc-text">如何验证我们的promise是否正确</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>Recent Post</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2022/10/12/04-%E5%89%8D%E7%AB%AF%EF%BC%88%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96%E7%AF%87%EF%BC%89/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96%E7%AF%87/" title="性能优化面试题"><img src= "" data-lazy-src="/img/%E5%A4%A9%E7%A9%BA.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="性能优化面试题"/></a><div class="content"><a class="title" href="/2022/10/12/04-%E5%89%8D%E7%AB%AF%EF%BC%88%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96%E7%AF%87%EF%BC%89/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96%E7%AF%87/" title="性能优化面试题">性能优化面试题</a><time datetime="2022-10-12T12:01:36.000Z" title="Created 2022-10-12 20:01:36">2022-10-12</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/10/11/05-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%96%B9%E6%B3%95%E5%AE%B6%E8%A7%84%EF%BC%89/JS%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%96%B9%E6%B3%95%E2%80%94%E2%80%94%E9%80%9F%E8%AE%B0%E5%B0%8F%E6%9C%AC%E5%AD%90/" title="JS字符串方法"><img src= "" data-lazy-src="/img/%E5%A4%A9%E7%A9%BA.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JS字符串方法"/></a><div class="content"><a class="title" href="/2022/10/11/05-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%96%B9%E6%B3%95%E5%AE%B6%E8%A7%84%EF%BC%89/JS%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%96%B9%E6%B3%95%E2%80%94%E2%80%94%E9%80%9F%E8%AE%B0%E5%B0%8F%E6%9C%AC%E5%AD%90/" title="JS字符串方法">JS字符串方法</a><time datetime="2022-10-11T12:01:36.000Z" title="Created 2022-10-11 20:01:36">2022-10-11</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/10/11/05-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%96%B9%E6%B3%95%E5%AE%B6%E8%A7%84%EF%BC%89/JS%E5%AF%B9%E8%B1%A1%E6%96%B9%E6%B3%95%E2%80%94%E2%80%94%E9%80%9F%E8%AE%B0%E5%B0%8F%E6%9C%AC%E5%AD%90/" title="JS对象方法"><img src= "" data-lazy-src="/img/%E5%A4%A9%E7%A9%BA.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JS对象方法"/></a><div class="content"><a class="title" href="/2022/10/11/05-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%96%B9%E6%B3%95%E5%AE%B6%E8%A7%84%EF%BC%89/JS%E5%AF%B9%E8%B1%A1%E6%96%B9%E6%B3%95%E2%80%94%E2%80%94%E9%80%9F%E8%AE%B0%E5%B0%8F%E6%9C%AC%E5%AD%90/" title="JS对象方法">JS对象方法</a><time datetime="2022-10-11T12:01:36.000Z" title="Created 2022-10-11 20:01:36">2022-10-11</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/10/11/05-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%96%B9%E6%B3%95%E5%AE%B6%E8%A7%84%EF%BC%89/JS%E6%95%B0%E7%BB%84%E6%96%B9%E6%B3%95%E2%80%94%E2%80%94%E9%80%9F%E6%9F%A5%E5%B0%8F%E6%9C%AC%E5%AD%90/" title="JS数组方法"><img src= "" data-lazy-src="/img/%E5%A4%A9%E7%A9%BA.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JS数组方法"/></a><div class="content"><a class="title" href="/2022/10/11/05-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%96%B9%E6%B3%95%E5%AE%B6%E8%A7%84%EF%BC%89/JS%E6%95%B0%E7%BB%84%E6%96%B9%E6%B3%95%E2%80%94%E2%80%94%E9%80%9F%E6%9F%A5%E5%B0%8F%E6%9C%AC%E5%AD%90/" title="JS数组方法">JS数组方法</a><time datetime="2022-10-11T12:01:36.000Z" title="Created 2022-10-11 20:01:36">2022-10-11</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/10/11/07-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%89%8B%E5%86%99%E7%AF%87%EF%BC%89/%E5%BC%80%E5%8F%91%E5%B0%81%E8%A3%85%E5%87%BD%E6%95%B0/" title="开发封装函数"><img src= "" data-lazy-src="/img/%E5%A4%A9%E7%A9%BA.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="开发封装函数"/></a><div class="content"><a class="title" href="/2022/10/11/07-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%89%8B%E5%86%99%E7%AF%87%EF%BC%89/%E5%BC%80%E5%8F%91%E5%B0%81%E8%A3%85%E5%87%BD%E6%95%B0/" title="开发封装函数">开发封装函数</a><time datetime="2022-10-11T12:01:36.000Z" title="Created 2022-10-11 20:01:36">2022-10-11</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2022 By 孙志豪</div><div class="framework-info"><span>Framework </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>Theme </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="Read Mode"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="Switch Between Light And Dark Mode"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="Toggle between single-column and double-column"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="Setting"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="Table Of Contents"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="Back To Top"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">Search</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  Loading the Database</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="Search for Posts" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>